package controller
{
	import flash.display.Screen;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import model.SlidePage;
	
	import mx.collections.ArrayCollection;
	
	import view.PageView;

	public class SlideShowController
	{
		private static var TIME_ON_PAGE:Number = 5000;
		public var slides:ArrayCollection;
		[Bindable] public var currentSlide:Number = 0;
		[Bindable] public var slide:PageView = new PageView();
		[Bindable] public var playing:Boolean = false;
		private var timer:Timer;
		
		public function SlideShowController(slides:ArrayCollection)
		{
			this.slides = slides;
			this.timer = new Timer(TIME_ON_PAGE);
			this.timer.addEventListener(TimerEvent.TIMER, timerHandler);
		}
		
		public function reset():void
		{
			this.currentSlide = 0;
			setSlideToPageView();
		}
		
		public function nextSlide(playTransition:Boolean):void
		{
			if (this.currentSlide != this.slides.length - 1)
			{
				this.currentSlide = this.currentSlide + 1;
				setSlideToPageView();
			}
		}
		
		public function previousSlide():void
		{
			if (this.currentSlide != 0)
			{
				this.currentSlide = this.currentSlide - 1;
				setSlideToPageView();
			}
		}
		
		public function getTotalSlides():int
		{
			return this.slides.length;
		}
		
		public function play():void
		{
			if (isCurrSlideLast())
			{
				reset();
			}
			
			this.playing = true;
			this.timer.start();
		}
		
		public function pause():void
		{
			this.playing = false;
			this.timer.stop();
		}
		
		public function playOrPause():void
		{
			if (this.playing)
			{
				pause();
			} else {
				play();
			}
		}
		
		public function isCurrSlideLast():Boolean
		{
			return this.currentSlide == getTotalSlides()-1;
		}
		
		private function setSlideToPageView():void
		{
			if (this.slides != null)
			{
				var slideData:SlidePage = this.slides.getItemAt(this.currentSlide) as SlidePage;
				var proportion:Number = Screen.mainScreen.bounds.height / slideData.pageHeight;
				this.slide.pageData = slideData;
				this.slide.width = slideData.pageWidth;
				this.slide.height = slideData.pageHeight;
				this.slide.scaleX = proportion;
				this.slide.scaleY = proportion;
			}
		}
		
		private function timerHandler(e:TimerEvent):void
		{
			if (isCurrSlideLast())
			{
				pause();
				return;
			}
			
			nextSlide(true);
		}
	}
}